package com.autohammal.ui.frame.data;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractViewer implements Viewer {
	private  ViewData masterView = null;
	private  ViewData originView = null;
	private List<ViewData> viewList = new ArrayList<ViewData>();

	public AbstractViewer() {
	}

	public AbstractViewer(ViewData originView) {
		setOriginView(originView);
	}

	public AbstractViewer(ViewData originView, ViewData masterView) {
		setOriginView(originView);
		setMasterView(masterView);
	}

	public ViewData getView(int index) {
		if (viewList.size() > 0 && index >= 0 && index < viewList.size())
			return viewList.get(index);
		return null;
	}

	@Override
	public ViewData getView(String viewName) {
		for (ViewData view : viewList) {
			if (view.getName().equals(viewName))
				return view;
		}
		return null;
	}

	@Override
	public void addView(ViewData view) {
		if (view != null && view.getName() != null) {
			if (viewList.add(view)) {
				if (view instanceof AbstractViewData) {
					AbstractViewData viewData = ((AbstractViewData) view);
					viewData.setViewer(this);
					switch (viewData.getViewState()) {
					case ORIGIN:
						setOriginView(viewData);
						setViewState(getOriginView(), ViewState.NORMAL);
						break;
					case MASTER:
						setMasterView(viewData);
						setViewState(getMasterView(), ViewState.NORMAL);
						break;
					default:
						setViewState(getMasterView(), ViewState.NORMAL);
						break;
					}
				}
			}
		}
	}

	protected void setViewState(ViewData viewdata, ViewState viewState) {
		if (viewdata != null && viewdata instanceof AbstractViewData) {
			((AbstractViewData) viewdata).setViewState(viewState);
		}
	}

	@Override
	public ViewData getMasterView() {
		if (masterView == null) {
			if (viewList.size() > 0) {
				setMasterView(viewList.get(0));
			}
		}
		return masterView;
	}

	public void setOriginView(ViewData originView) {
		this.originView = originView;
	}

	@Override
	public ViewData getOriginView() {
		if (originView == null) {
			setOriginView(getMasterView());
		}
		return originView;
	}

	public void setMasterView(ViewData masterView) {
		this.masterView = masterView;
	}

}
